import 'package:casdon/common/state/common_net_status.dart';

class LoginState {
  final CommonNetStatus status;
  final bool _agreed; // 是否同意协议
  final String? errorCode; // 错误码,只有failure状态下有值，且值有意义
  final String? message;
  final int version; // 新增字段，递增版本号，用于强制刷新UI，防止同样的state无法再次出发点

  bool get agreed => _agreed; // 公共只读 getter

  static const Object _sentinel = Object();

  LoginState({
    required this.status,
    bool agreed = false, // 修正：使用固定默认值而不是实例变量
    this.message,
    this.errorCode,
    required this.version,
  }) : _agreed = agreed;

  LoginState.initial()
    : status = CommonNetStatus.idle,
      _agreed = false,
      errorCode = null,
      message = null,
      version = 1;

  LoginState toIdle() => copyWith(
    status: CommonNetStatus.idle,
    version: version + 1,
    agreed: false,
    errorCode: null,
    message: null,
  );

  LoginState toLoading() => copyWith(
    status: CommonNetStatus.loading,
    version: version + 1,
    agreed: _agreed, // 修正：使用 _agreed
    errorCode: null,
    message: null,
  );

  LoginState toSuccess([String? msg]) => copyWith(
    status: CommonNetStatus.success,
    message: msg,
    version: version + 1,
    agreed: _agreed, // 修正：使用 _agreed
    errorCode: null,
  );

  LoginState toFailure({String? errorCode, required String msg}) => copyWith(
    status: CommonNetStatus.failure,
    message: msg,
    version: version + 1,
    agreed: _agreed, // 修正：使用 _agreed
    errorCode: errorCode,
  );

  LoginState setAgree(bool val) => copyWith(
    agreed: val,
    version: version + 1,
    status: CommonNetStatus.idle,
    message: "",
    errorCode: "0",
  );

  @override
  bool operator ==(Object other) {
    return other is LoginState &&
        other.status == status &&
        other.message == message &&
        other.version == version &&
        other._agreed == _agreed &&
        other.errorCode == errorCode;
  }

  @override
  int get hashCode => Object.hash(status, message, version, _agreed);

  LoginState copyWith({
    Object? status = _sentinel,
    Object? message = _sentinel,
    Object? version = _sentinel,
    Object? agreed = _sentinel,
    Object? errorCode = _sentinel,
  }) {
    return LoginState(
      status: status == _sentinel
          ? this.status
          : status as CommonNetStatus? ?? this.status,
      message: message == _sentinel
          ? this.message
          : message as String? ?? this.message,
      version: version == _sentinel
          ? this.version
          : version as int? ?? this.version,
      agreed: agreed == _sentinel
          ? this.agreed
          : agreed as bool? ?? this.agreed,
      errorCode: errorCode == _sentinel
          ? this.errorCode
          : errorCode as String? ?? this.errorCode,
    );
  }
}
